<?php
/*                            _ooOoo_
 *                           o8888888o
 *                           88" . "88
 *                           (| -_- |)
 *                            O\ = /O
 *                        ____/`---'\____
 *                      .   ' \\| |// `.
 *                       / \\||| : |||// \
 *                     / _||||| -:- |||||- \
 *                       | | \\\ - /// | |
 *                     | \_| ''\---/'' | |
 *                      \ .-\__ `-` ___/-. /
 *                   ___`. .' /--.--\ `. . __
 *                ."" '< `.___\_<|>_/___.' >'"".
 *               | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *                 \ \ `-. \_ __\ /__ _/ .-` / /
 *         ======`-.____`-.___\_____/___.-`____.-'======
 *                            `=---='
 *
 *         .............................................
 *                  佛祖保佑             永无BUG
 *
 * ======================================================
 * @author: Ethan Lu <ethan.lu@qq.com>
 * 
 */

namespace common\behaviors;


use yii\base\Behavior;
use yii\db\ActiveRecord;

class AttributeValueBehavior extends Behavior
{

    /** @var  ActiveRecord */
    public $owner;

    /**
     * 存储的数据
     */
    public $data;

    /**
     * 关联字段
     */
    public $relationField = 'attr_id';

    /**
     * 关联表
     */
    public $relationTable;

    /**
     * 定义事件
     *
     * @return array
     */
    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
            ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
            ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete'
        ];
    }

    /**
     * 执行后查询关联数据
     */
    public function afterFind()
    {
        $this->owner->{$this->data} = $this->owner->{$this->relationTable};
    }

    /**
     * 写入新数据到关联表
     */
    public function afterInsert()
    {
        if($this->owner->{$this->data}) {
            $this->saveDataRelation($this->owner->{$this->data});
        }
    }


    public function afterUpdate()
    {
        // 获取数据库中已存在的数据
        $models = $this->owner->{$this->relationTable};
        // 提交的数据
        $attributes = $this->owner->{$this->data};

        xdebug_var_dump($models, $attributes);
        die;
        // 新属性
        $newAttribute = [];
        foreach($models as $model) {
            $attr = $model->toArray(['attribute_id', 'value']);
            if(!in_array($attr, $attributes)) {
                $model->delete();
            }
        }

        $modelsArray = $this->getPostAttributes($models);
        foreach($attributes as $attr) {
            if(!in_array($attr, $modelsArray)) {
                if(!empty($attr['value'])) {
                    $newAttribute[] = $attr;
                }
            }
        }
        $this->saveDataRelation($newAttribute);
    }


    public function afterDelete()
    {
        /** @var ActiveRecord $modelClass */
        $modelClass = $this->getRelation()->modelClass;
        /** @var ActiveRecord $model */
        $model = new $modelClass;
        $model->deleteAll([
            $this->relationField => $this->owner->getPrimaryKey()
        ]);
    }


    /**
     * @return \yii\db\ActiveQuery|\yii\db\ActiveQueryInterface
     */
    protected function getRelation()
    {
        return $this->owner->getRelation($this->relationTable);
    }

    /**
     * 保存关联属性
     * @param $datas
     */
    protected function saveDataRelation($datas)
    {

        $modelClass = $this->getRelation()->modelClass;
        foreach ($datas as $data) {
            /** @var ActiveRecord $model */
            $model = new $modelClass;
            $model->load($data, '');
            $this->owner->link($this->relationTable, $model);
        }
    }

//    private function enrichData($data)
//    {
//        $attributes = [];
//
//        // 获取属性id
//        $attribute_ids = array_unique(ArrayHelper::getColumn($data, 'attribute_id'));
//
//
//        foreach($attribute_ids as $index => $id) {
//            $attributes[$id] = $data[$index];
//            $value = [];
//            foreach($data as $k => $v) {
//                if($id == $v->attribute_id) {
//                    array_push($value, $v->value);
//                }
//            }
//            $attributes[$id]->value = $value;
//        }
//        return $attributes;
//    }


}